package com.aqie.easy.bitOperation;

import com.aqie.libs.StdOut;

/**
 * 342 4的幂
 */
public class IsPowerOfFour {
    /**
     * 1. 迭代 5ms,
     * @param num
     * @return
     */
    public static boolean isPowerOfFour(int num) {
        if (num < 1) return false;
        while (num % 4 == 0){
            num /= 4;
        }
        return num == 1;
    }

    /**
     * 2, 位运算 只有奇数位有且只有一个1，偶数位都是0  a=1010  6ms
     * @param num
     * @return
     */
    public static boolean isPowerOfFour2(int num) {
        return (num & 0xaaaaaaaa) == 0 && Integer.bitCount(num) == 1;
    }

    /**
     * 3. 位运算 6ms
     * @param num
     * @return
     */
    public static boolean isPowerOfFour3(int num) {
        if (num < 0 || (num & (num-1)) != 0){//check(is or not) a power of 2.
            return false;
        }
        return (num & 0x55555555) != 0;//check 1 on odd bits
    }

    /**
     * 4.位运算 6ms
     * @param num
     * @return
     */
    public static boolean isPowerOfFour4(int num) {
        if (num < 0 || (num & (num-1)) != 0){//check(is or not) a power of 2.
            return false;
        }
        return num % 3 == 1;
    }

    public static void main(String[] args) {
        StdOut.println(5 % 4);
        StdOut.println(5 / 4);
        StdOut.println(isPowerOfFour3(5));
    }
}
